<?php

namespace app\push\controller;

use think\Controller;
use think\Db;
use app\push\model\ChatRooms;


class Index extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        //回话列表
        $ChatRooms = new ChatRooms();
        $where = "(user_id = " . getSessInfo('id') . " AND is_u_show = 1) OR (other_id = " . getSessInfo('id') . "  AND is_o_show = 1)";
        $where .= ' OR (ids like "%,' . getSessInfo('id') . ',%" and hideids NOT LIKE "%,' . getSessInfo('id') . ',%")';
        $order = 'update_time desc';

        $rooms_list = $ChatRooms->getlist($where, [], $order);

        //群聊
        $where = [
            'ids' => ['like', '%,' . getSessInfo('id') . ',%'],
        ];
        $group = db('chat_rooms')->where($where)->select();


        //好友
        $where = [
            'user_id' => getSessInfo('id'),
        ];
        $friend = db('user_friend')->where($where)->select();
        $arr = ['A' => [], 'B' => [], 'C' => [], 'D' => [], 'E' => [], 'F' => [], 'G' => [], 'H' => [], 'I' => [], 'G' => [], 'L' => [], 'M' => [], 'N' => [], 'O' => [], 'P' => [], 'Q' => [], 'R' => [], 'S' => [], 'T' => [], 'U' => [], 'V' => [], 'W' => [], 'X' => [], 'Y' => [], 'Z' => [], '#' => []];
        $pinyin = new \Pinyin\Pinyin();

        if ($friend) {
            foreach ($friend as $key => $value) {
                $user = db('user')->where('id', $value['other_id'])->find();
                $user['room'] = $value;
                $ide = @strtoupper($pinyin->encode($user['ide']));
                if (isset($arr[$ide])) {
                    $arr[$ide][] = $user;
                }
            }
        }

        //查找新消息
        $where = [
            'user_id' => getSessInfo('id'),
            'u_unread' => 1
        ];
        $newchat = db('chat_rooms')->where($where)->count();

        $where = [
            'other_id' => getSessInfo('id'),
            'o_unread' => 1
        ];
        $newchat2 = db('chat_rooms')->where($where)->count();

        //查找新朋友
        $where = [
            'other_id' => getSessInfo('id'),
            'status' => 0
        ];
        $newfriend = db('user_friend_log')->where($where)->count();

        $this->assign('newchat', ($newchat + $newchat2));
        $this->assign('newfriend', $newfriend);
        $this->assign('arr', $arr);
        $this->assign('group', $group);
        $this->assign('rooms_list', $rooms_list);
        $this->assign('user_id', getSessInfo('id'));
        return view();
    }

    /**
     * 加载历史记录
     */
    public function getRoomsDetails()
    {
        $id = input('id');
        if (!$id) {
            $this->error('网络连接超时，拉去历史记录失败！');
        }
        db('chat_rooms')->where('id', $id)->update([
            'o_unread' => '0',
            'u_unread' => '0',
        ]);

        $list = db('chat_details')->where('room_id', $id)->order('id desc')->limit(10)->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['user'] = db('user')->where('id', $value['user_id'])->find();
                $list[$key]['content'] = userTextDecode($value['content']);
            }
        }
        $this->success('获取成功', '', $list);
    }

    /**
     * 更新未读消息状态
     */
    public function updateRoomsStatus($id = 0)
    {
        if ($id) {
            db('chat_rooms')->where('id', $id)->update([
                'o_unread' => '0',
                'u_unread' => '0',
            ]);
            $this->success("更新成功");
        }
    }

    /**
     * 删除列表
     */
    public function dellist()
    {
        $id = input('id');
        $user = input('user');
        $type = input('type');
        $group = input('group');
        if ($group == 1) {
            if (!$id) {
                $this->error('移除失败');
            }
            $where = [
                'id' => $id
            ];
            $info = db('chat_rooms')->where($where)->find();
            $ids = str2arr($info['hideids']);
            if (@in_array(getSessInfo('id'), $ids)) {
                $this->error('移除成功');
            }
            $ids = array_filter($ids);
            if ($ids) {
                $ids = "0," . arr2str($ids) . ',' . getSessInfo('id') . ',0';
            } else {
                $ids = "0," . getSessInfo('id') . ',0';
            }
            $result = db('chat_rooms')->where($where)->setField('hideids', $ids);
        } else {
            if (!$id || !$user || !$type) {
                $this->error('移除失败');
            }
            $where = [
                'id' => $id,
            ];
            if ($type == 'is_o_show') {
                $where['other_id'] = $user;
            } else {
                $where['user_id'] = $user;
            }
            // halt($where);
            $result = db('chat_rooms')->where($where)->setField($type, 0);
        }

        if ($result) {
            $this->success('移除成功');
        } else {
            $this->error('移除失败');
        }
    }


    /**
     * 添加朋友
     */
    public function addfriend()
    {
        if (request()->ispost()) {
            $param = input();
            if (!$param['id']) {
                $this->error('数据异常');
            }
            $where = [
                'user_id' => getSessInfo('id'),
                'other_id' => $param['id'],
            ];
            $info = db('user_friend_log')->where($where)->find();
            if ($info) {
                $this->success('已发送添加请求');
            }
            $data = [
                'user_id' => getSessInfo('id'),
                'other_id' => $param['id'],
                'status' => 0,
                'remark' => $param['remark'],
                'created_time' => time(),
            ];
            $result = db('user_friend_log')->insert($data);
            if ($result) {
                $this->success('发送请求成功');
            } else {
                $this->error('发送请求失败');
            }
        } else {
            return view();
        }
    }


    /**
     * 查找朋友
     */
    public function getUserFriend($key)
    {
        if (!$key) {
            $this->error('请输入手机号码');
        }
        if ($key == getSessInfo('account')) {
            $this->error('不可添加自己为好友');
        }
        $info = db('user')->field('id,account,nickname,ide')->where('account', $key)->find();
        if (!$info) {
            $this->error('没有查找到该用户');
        }
        $where = [
            'user_id' => getSessInfo('id'),
            'other_id' => $info['id']
        ];
        if (db('user_friend')->where($where)->find()) {
            $this->error('该用户已经是您的好友');
        }
        $this->success('查找完成', '', $info);
    }


    /**
     * 移除标记
     */
    public function ide_friend($status)
    {
        if ($status == 1) {
            $where = [
                'other_id' => getSessInfo('id'),
                'status' => 0
            ];
            db('user_friend_log')->where($where)->setField('status', 1);
        }
        $where = [
            'other_id' => getSessInfo('id'),
        ];
        $list = db('user_friend_log')->where($where)->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['user'] = db('user')->field('id,account,nickname,ide')->where('id', $value['user_id'])->find();
                if ($value['status'] > 1) {
                    $list[$key]['button']  = '已添加';
                    $list[$key]['class']  = 'btn-default';
                } else {
                    $list[$key]['button']  = '添加';
                    $list[$key]['class']  = 'btn-info';
                }
            }
        }
        $this->success('获取数据', '', $list);
    }


    /**
     * 确认添加好友
     */
    public function confirm_friend($id)
    {
        if (!$id) {
            $this->error('数据异常');
        }
        $info = db('user_friend_log')->find($id);
        if (!$info) {
            $this->error('数据异常');
        }
        if ($info['other_id'] != getSessInfo('id')) {
            $this->error('数据异常');
        }
        if ($info['status'] == 2) {
            $this->error('已添加好友');
        }
        $data[] = [
            'user_id' => $info['user_id'],
            'other_id' => $info['other_id'],
            'created_time' => time(),
            'status' => 0
        ];
        $data[] = [
            'user_id' => $info['other_id'],
            'other_id' => $info['user_id'],
            'created_time' => time(),
            'status' => 0
        ];
        db('user_friend')->insertAll($data);
        db('user_friend_log')->where('id', $id)->setField('status', 2);
        $this->success('添加成功', '', ($info['user_id'] == getSessInfo('id')) ? $info['other_id'] : $info['user_id']);
    }

    /**
     * 获取好友列表
     */
    public function getFriend()
    {
        //好友
        $where = [
            'user_id' => getSessInfo('id'),
        ];
        $friend = db('user_friend')->where($where)->select();
        $arr = ['A' => [], 'B' => [], 'C' => [], 'D' => [], 'E' => [], 'F' => [], 'G' => [], 'H' => [], 'I' => [], 'G' => [], 'L' => [], 'M' => [], 'N' => [], 'O' => [], 'P' => [], 'Q' => [], 'R' => [], 'S' => [], 'T' => [], 'U' => [], 'V' => [], 'W' => [], 'X' => [], 'Y' => [], 'Z' => [], '#' => []];
        $pinyin = new \Pinyin\Pinyin();

        if ($friend) {
            foreach ($friend as $key => $value) {
                $user = db('user')->where('id', $value['other_id'])->find();
                $user['room'] = $value;
                $ide = @strtoupper($pinyin->encode($user['ide']));
                if (isset($arr[$ide])) {
                    $arr[$ide][] = $user;
                }
            }
        }
        $this->assign('list', $arr);
        return view('friend_list');
    }

    /**
     * 好友详情
     */
    public function friend_info($id)
    {
        $info = db('user')->find($id);
        $this->assign('info', $info);
        return view();
    }

    /**
     * 创建好友聊天
     */
    public function create_friend($id)
    {
        $user = db('user')->field('id,nickname,ide,account')->where('id', $id)->find();
        $where = [
            'user_id' => getSessInfo('id'),
            'other_id' => $id,
        ];
        $info = db('chat_rooms')->where($where)->find();
        if (!$info) {
            $where = [
                'other_id' => getSessInfo('id'),
                'user_id' => $id,
            ];
            $info = db('chat_rooms')->where($where)->find();
        }
        if (!$info) {
            $info = [
                'type' => 2,
                'user_id' => getSessInfo('id'),
                'other_id' => $id,
                'created_time' => time(),
                'hideids' => 0,
                'ids' => 0,
                'is_u_show' => 1,
            ];
            $info['id'] = db('chat_rooms')->insertGetId($info);
            $info['user'] = $user;
            $info['time'] = date('H:i');
            $info['is_o'] = 'is_o_show';
            $this->success('新增好友', '', $info);
        } else {
            $info['user'] = $user;
            $info['time'] = date('H:i');
            $info['is_o'] = 'is_u_show';
            $this->success('已有好友', '', $info);
        }
    }

    /**
     * 群聊
     */
    public function addgroup()
    {
        if (request()->ispost()) {
            $param = input();
            if (!input('group_name')) {
                $this->error('请输入群聊名称');
            }
            if (!$param['ids']) {
                $this->error('请选择群聊用户');
            }
            $ids = $param['ids'];
            $hideids = '0,' . arr2str($ids) . ',0';
            array_push($ids, getSessInfo('id'));
            $ids = '0,' . arr2str($ids) . ',0';
            $name = cutstr(trim(input('group_name')), 0, 1);
            $data = [
                'type' => 1,
                'created_time' => time(),
                'ids' => $ids,
                'hideids' => $hideids,
                'group_name' => input('group_name'),
                'ide' => $name ? $name : '群',
            ];
            $data['id'] = db('chat_rooms')->insertGetId($data);
            $data['allids'] = $ids;
            if ($data['id']) {
                $this->success('创建成功', '', $data);
            } else {
                $this->error('创建失败');
            }
        } else {
            //好友
            $where = [
                'user_id' => getSessInfo('id'),
            ];
            $friend = db('user_friend')->where($where)->select();
            $arr = ['A' => [], 'B' => [], 'C' => [], 'D' => [], 'E' => [], 'F' => [], 'G' => [], 'H' => [], 'I' => [], 'G' => [], 'L' => [], 'M' => [], 'N' => [], 'O' => [], 'P' => [], 'Q' => [], 'R' => [], 'S' => [], 'T' => [], 'U' => [], 'V' => [], 'W' => [], 'X' => [], 'Y' => [], 'Z' => [], '#' => []];
            $pinyin = new \Pinyin\Pinyin();

            if ($friend) {
                foreach ($friend as $key => $value) {
                    $user = db('user')->where('id', $value['other_id'])->find();
                    $user['room'] = $value;
                    $ide = @strtoupper($pinyin->encode($user['ide']));
                    if (isset($arr[$ide])) {
                        $arr[$ide][] = $user;
                    }
                }
            }
            $this->assign('list', $arr);
            return view();
        }
    }

    /**
     * 获取群组
     */
    public function getGroup()
    {
        //群聊
        $where = [
            'ids' => ['like', '%,' . getSessInfo('id') . ',%'],
        ];
        $group = db('chat_rooms')->where($where)->select();
        $this->assign('group', $group);
        return view('group_list');
    }

    /**
     * 群组详情
     */
    public function group_info($id)
    {
        $info = db('chat_rooms')->find($id);
        $this->assign('info', $info);
        return view();
    }
}
